package com.ruoyi.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.domain.entity.*;
import com.ruoyi.project.domain.query.ProjectCustomQuery;
import com.ruoyi.project.domain.query.ProjectFeeQuery;
import com.ruoyi.project.domain.query.ProjectSaleQuery;
import com.ruoyi.project.mapper.ProjectDetailLogMapper;
import com.ruoyi.project.service.IProjectCustomerService;
import com.ruoyi.project.service.IProjectFeeService;
import com.ruoyi.project.service.IProjectSaleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/project/customer")
public class ProjectCustomerController {

    @Resource
    private IProjectCustomerService customerService;

    @Resource
    private IProjectSaleService saleService;

    @Resource
    ProjectDetailLogMapper projectDetailLogMapper;


    @PutMapping("/issueMoney")
    public R issueMoney(@RequestBody ProjectCustom project) {
        //1.获取个人绩效总金额
        BigDecimal personTotal = project.getPersonTotal() != null ? project.getPersonTotal() : BigDecimal.ZERO;
        //2.个人绩效待发放
        BigDecimal personWait = project.getPersonWait() != null ? project.getPersonWait() : BigDecimal.ZERO;
        //3.本次发放的
        BigDecimal personCurrent = project.getPersonCurrent() != null ? project.getPersonCurrent() : BigDecimal.ZERO;
        if (personCurrent.compareTo(personWait) > 0) {
            throw new RuntimeException("个人本次发放金额不能超过待发放金额");
        }

        //4.个人绩效已发放 需要加上本次发放的
        BigDecimal personAlready = project.getPersonAlready() != null ? project.getPersonAlready() : BigDecimal.ZERO;
        personAlready = personAlready.add(personCurrent);
        project.setPersonAlready(personAlready);

        //计算待发放的  个人总的 - 已发放的
        BigDecimal perWait = personTotal.subtract(personAlready);
        project.setPersonWait(perWait);

        //===部门的
        //1.获取部门绩效总金额
        BigDecimal deptTotal = project.getDeptTotal() != null ? project.getDeptTotal() : BigDecimal.ZERO;
        //2.部门绩效待发放
        BigDecimal deptWait = project.getDeptWait() != null ? project.getDeptWait() : BigDecimal.ZERO;
        //3.本次发放的
        BigDecimal deptCurrent = project.getDeptCurrent() != null ? project.getDeptCurrent() : BigDecimal.ZERO;
        if (deptCurrent.compareTo(deptWait) > 0) {
            throw new RuntimeException("部门本次发放金额不能超过待发放金额");
        }

        //4.个人绩效已发放 需要加上本次发放的
        BigDecimal deptAlready = project.getDeptAlready() != null ? project.getDeptAlready() : BigDecimal.ZERO;
        deptAlready = deptAlready.add(deptCurrent);
        project.setDeptAlready(deptAlready);

        //计算待发放的  部门总的 - 已发放的
        BigDecimal depWait = deptTotal.subtract(deptAlready);
        project.setDeptWait(depWait);

        //插入日志
        ProjectDetailLog log = new ProjectDetailLog();
        log.setProjectNo(project.getCustomerId());
        log.setDetailId(project.getId());
        log.setPersonName(project.getSaleName() != null ? project.getSaleName() : project.getPromoterName());

        log.setPersonCurrent(project.getPersonCurrent());
        log.setPersonTotalt(project.getPersonTotal());
        log.setPersonWait(project.getPersonWait());

        log.setDeptCurrent(project.getDeptCurrent());
        log.setDeptTotalt(project.getDeptTotal());
        log.setDeptWait(project.getDeptWait());

        log.setIssueType("2");
        log.setPersonId(project.getSaleId() != null ? project.getSaleId() : project.getPromoterId());

        projectDetailLogMapper.insert(log);

        customerService.updateById(project);

        return R.ok();
    }

    @ApiOperation("分页")
    @GetMapping(value = "/list")
    public R<TableDataInfo> page(ProjectCustomQuery query) {
        //查询自己创建的项目
        Long userId = SecurityUtils.getUserId();
        Page<Object> page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        LambdaQueryWrapper<ProjectCustom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(query.getStatus() != null, ProjectCustom::getStatus, query.getStatus());
        wrapper.like(query.getPromoterName() != null, ProjectCustom::getPromoterName, query.getPromoterName());
        wrapper.like(query.getSaleName() != null, ProjectCustom::getSaleName, query.getSaleName());

        if (SecurityUtils.hasRole("admin") || SecurityUtils.hasRole("gjadmin")) {

        } else {
            wrapper.eq(ProjectCustom::getPromoterId, userId)
                    .or()
                    .eq(ProjectCustom::getSaleId, userId);
        }
        List<ProjectCustom> list = customerService.list(wrapper);
        return R.ok(new TableDataInfo(list, page.getTotal()));
    }


    @ApiOperation("按人员统计")
    @GetMapping(value = "/merge")
    public List<ProjectCustom> merge(ProjectCustomQuery query) {
        //查询自己创建的项目
        Long userId = SecurityUtils.getUserId();
        Page<Object> page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        LambdaQueryWrapper<ProjectCustom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(query.getStatus() != null, ProjectCustom::getStatus, query.getStatus());
        wrapper.like(query.getPromoterName() != null, ProjectCustom::getPromoterName, query.getPromoterName());
        wrapper.like(query.getSaleName() != null, ProjectCustom::getSaleName, query.getSaleName());

        if (SecurityUtils.hasRole("admin") || SecurityUtils.hasRole("gjadmin")) {

        } else {
            wrapper.eq(ProjectCustom::getPromoterId, userId)
                    .or()
                    .eq(ProjectCustom::getSaleId, userId);
        }
        List<ProjectCustom> list = customerService.selectGroupBySaleId(query);
        return list;
    }


    @ApiOperation("分页")
    @GetMapping(value = "/auditList")
    public R auditList() {
        //查询自己创建的项目
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ProjectCustom> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectCustom::getStatus, "1");
        List<ProjectCustom> list = customerService.list(wrapper);
        return R.ok(list);
    }


    @ApiOperation("新增")
    @PostMapping
    public R save(@RequestBody ProjectCustom project) {
        //新增status设置为1    1待审核 2审核通过 3作废

        //同一个往来客户 时间不能交叉

        boolean add = checkDate(project, "add");
        if (add) {
            throw new RuntimeException("此次申报的往来客户与已经申报的时间上存在交叉，请重新选择起始日期和截止日期");
        }
        project.setAuditName("吴治国");
        project.setPromoterId(SecurityUtils.getUserId());
        project.setPromoterName(SecurityUtils.getLoginUser().getUser().getNickName());
        project.setStatus("1");
        return R.ok(customerService.save(project));
    }

    public boolean checkDate(ProjectCustom project, String type) {
        Long userId = SecurityUtils.getUserId();
        // 假设日期不为空
        Date startDate = project.getStartDate();     // A 开始
        Date endDate = project.getEndDate();         // A 结束
        boolean isOverlap = false;
        if (type.equals("add")) {
            LambdaQueryWrapper<ProjectCustom> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProjectCustom::getCustomerId, project.getCustomerId());
            List<ProjectCustom> customList = customerService.list(wrapper);
            for (ProjectCustom custom : customList) {
                Date customStartDate = custom.getStartDate();   // B 开始
                Date customEndDate = custom.getEndDate();       // B 结束
                // 判断两个时间段是否有交叉
                isOverlap = !(endDate.compareTo(customStartDate) < 0 ||
                        customEndDate.compareTo(startDate) < 0);
                if (isOverlap) {//存在交叉
                    break;
                }
            }

        } else {
            //如果是修改  先排除修改的这条数据
            LambdaQueryWrapper<ProjectCustom> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProjectCustom::getCustomerId, project.getCustomerId());
            wrapper.eq(ProjectCustom::getPromoterId, userId);

            wrapper.ne(ProjectCustom::getId, project.getId());

            List<ProjectCustom> customList = customerService.list(wrapper);
            for (ProjectCustom custom : customList) {
                Date customStartDate = custom.getStartDate();   // B 开始
                Date customEndDate = custom.getEndDate();       // B 结束
                // 判断两个时间段是否有交叉
                isOverlap = !(endDate.compareTo(customStartDate) < 0 ||
                        customEndDate.compareTo(startDate) < 0);
                if (isOverlap) {//存在交叉
                    break;
                }
            }
        }
        //true 存在交叉 false不存在
        return isOverlap;
    }


    @ApiOperation("修改")
    @PutMapping
    public R update(@RequestBody ProjectCustom project) {
        boolean edit = checkDate(project, "edit");
        if (edit) {
            throw new RuntimeException("该往来客户起始日期或截至日期存在交叉");
        }

        return R.ok(customerService.updateById(project));
    }

    @ApiOperation("修改")
    @PutMapping("/updateSubAmount")
    public R updateSubAmount(@RequestBody ProjectCustom project) {
        if (project.getId() == null) {
            throw new RuntimeException("修改失败");
        }

        ProjectCustom byId = customerService.getById(project.getId());
        byId.setSubAmount(project.getSubAmount());

        return R.ok(customerService.updateById(byId));
    }


    @ApiOperation("审核")
    @PutMapping("/audit")
    public R audit(@RequestBody ProjectCustom project) {
        project.setAuditId(SecurityUtils.getUserId());
        project.setAuditName(SecurityUtils.getLoginUser().getUser().getNickName());
        return R.ok(customerService.updateById(project));
    }


    @ApiOperation("删除")
    @DeleteMapping(value = "/{id}")
    public R delete(@PathVariable("id") Long id) {
        return R.ok(customerService.removeById(id));
    }


    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") Long id) {
        return R.ok(customerService.getById(id));
    }


}
